import cv2
import pytesseract
import pyautogui
import numpy as np
import os
from PIL import ImageGrab,Image
import time

def getpngfromShot(_small,_big,_threshold=0.8,_show=False):
    time.sleep(1)
    
    # small = cv2.imread("xing/guide.png")
    # img = pyautogui.screenshot(region=[0,0,1618,946])
    small = np.asarray(_small)
    shot = cv2.cvtColor(np.asarray(_big),cv2.COLOR_RGB2BGR)

    s_h,s_w = small.shape[:2]
    # print(s_w,s_h)
    result = cv2.matchTemplate(shot,small,cv2.TM_CCOEFF_NORMED)

    threshold = _threshold

    locations = np.where(result >= threshold)
    # print(locations)

    sum  = 0
    locs = zip(*locations[::-1])
    if len(list(locs)) == 0: return 0
    for loc in zip(*locations[::-1]):
        # print("loc",loc)
        cv2.rectangle(shot,loc,(loc[0]+s_w,loc[1]+s_h),(0,255,0),2)
        sum = sum + 1
        break
    # print(sum)

    if _show:
        cv2.imshow("Result",shot)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    # cv2.imwrite('shot.jpg', shot) # save
     
    return loc

def getSP(img):
    # region = (x+1370,y+77,x+1410,y+104)
    # region = (x+1233,y+82,x+1269,y+102)
    # screenshot = ImageGrab.grab(bbox=region)
    # screenshot.save("xing\sp.png")
    img.save("xing\sp.png")
    # screenshot.show()
    image = np.asarray(img)
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    _,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    custom_config = r'--oem 3 --psm 6 outputbase digits'
    text = pytesseract.image_to_string(thresh,config=custom_config)
    if text == "":
        print("ocr text = null")
        return 0
    else:
        print(f"ocr text ={text}")
        if text.strip().isdigit():
            return int(text)
        else:
            return -1

if __name__ == "__main__":
    while True:
        sp_region = (1236,81,1269,102)
        sp_img = ImageGrab.grab(bbox=sp_region)
        sp = getSP(sp_img)
        time.sleep(0.5)


def needSP(what):
    拟造花萼_赤 = [

    ]
    凝滞虚影 = [
        '燔灼之形',
        '空海之形',
        '巽风之形',
        '鸣雷之形',
        '炎华之形',
        '锋芒之形',
        '霜晶之形',
        '幻光之形',
        '冰棱之形',
        '震厄之形',
        '偃偶之形',
        '孽兽之形',
        '天人之形',
        '幽府之形',
        '冰酿之形',
        '焦炙之形',
        '嗔怒之形',
        '职司之形',
    ]
    历战余响 = [
        '毁灭的开端',
        '寒潮的落幕',
        '不死的神实',
        '蛀星的旧靥',
        '尘梦的赞礼',
    ]
    for item in 凝滞虚影:
        if item == what:
            return 30
    for item in 历战余响:
        if item == what:
            return 30
    return 10